<?php

namespace app\Http\Controllers\admins;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class Groups extends Controller
{
    // 表单
    private function form($field = [])
    {
        $form = [
            ['label' => '角色名称', 'name' => 'title', 'verify' => 'required'],
        ];
        if ($field) {
            if (count($field) === count($field, 1)) {
                array_push($form, $field);
            } else {
                $form = array_merge($form, $field);
            }
        }
        return $form;
    }

    // 树形角色菜单
    private function rights($default = [])
    {
        $db = DB::table('admin_menus')
            ->orderBy('ord', 'desc')
            ->get()
            ->all();
        $db = $this->trees($db);
        $db = array_reduce($db, function ($res, $next) use ($default) {
            $res[] = '<li style="padding-left:' . ($next->level * 2) . 'em;"><input type="checkbox" name="rights[]" title="' . ($next->level === 0 ? '<strong>' : '|— ') . $next->title . ($next->level === 0 ? '</strong>' : '') . '" value=' . $next->id . (in_array($next->id, $default) ? ' checked' : '') . ' lay-skin="primary" class="layui-input"></li>';
            return $res;
        }, []);
        return '<ul>' . implode("\n", $db) . '</ul>';
    }

    public function index(Request $request)
    {
        if ($request->ajax()) {
            // $page = $request->page ?? 1;
            $limit = $request->limit ?? 10;
            $db = DB::table('admin_group');
            // 搜索
            if (isset($request->search) && $request->search) {
                foreach ((array)$request->search as $k => $v) {
                    if ($v) $db = $db->where($k, 'like', "%{$v}%");
                }
            }
            $data['count'] = $db->count();
            // 分页
            $db = $db->paginate($limit)->items();
            if ($data['count']) {
                $data['code'] = 0;
            } else {
                $data['code'] = 1;
                $data['msg'] = '暂无记录';
            }
            $data['data'] = $db;
            return json_encode($data);
        }
        $form = [
            ['label' => '搜索ID', 'name' => 'id', 'layui' => 'inline', 'placeholder' => '请输入'],
            ['label' => '角色名称', 'name' => 'title', 'layui' => 'inline', 'placeholder' => '请输入'],
            ['type' => 'submit', 'filter' => 'search', 'layui' => 'inline', 'value' => '<i class="layui-icon layui-icon-search"></i>']
        ];
        $data['search'] = $this->build_form($form);
        $data['title'] = '角色列表';
        $data['prefix'] = '/admins/groups';
        return view('/admins/groups/index', $data);
    }

    public function add()
    {
        $data['title'] = '添加';
        $form = $this->form([
            ['label' => '权限菜单', 'type' => 'html', 'value' => $this->rights()],
            ['type' => 'submit', 'value' => '保存'],
            ['type' => 'button', 'value' => '取消', 'filter' => 'cancel', 'btn' => 'primary']
        ]);
        $args = ['url' => '/admins/groups/save', 'reload' => 'parent.location'];
        $data['form'] = $this->build_form($form);
        $data['script'] = $this->build_script($form, $args);
        return view('/admins/groups/add', $data);
    }

    public function save(Request $request)
    {
        $data = $this->check($this->form(), $request);
        if (!is_array($data)) return $data;
        $check = DB::table('admin_group')->where('title', $request->title)->first();
        if ($check) return $this->errMsg(1, '角色名称已存在');
        $data['rights'] = json_encode(array_map('intval', array_values((array)$request->rights)));
        $res = DB::table('admin_group')->insert($data);
        if (!$res) $this->errMsg(1, '保存失败');
        return $this->errMsg(0, '保存成功');
    }

    public function edit(Request $request)
    {
        $id = (int)$request->id;
        if (!$id) return $this->errMsg(1, '数据错误');
        $value = DB::table('admin_group')->where('id', $id)->first();
        $default = (array)json_decode($value->rights);
        $form = $this->form([
            ['label' => '权限菜单', 'type' => 'html', 'value' => $this->rights($default)],
            ['name' => 'id', 'type' => 'hidden', 'value' => $id],
            ['type' => 'submit', 'value' => '保存'],
            ['type' => 'button', 'value' => '取消', 'filter' => 'cancel', 'btn' => 'primary']
        ]);
        $args = ['url' => '/admins/groups/save_edit', 'reload' => 'dataTable'];
        $data['title'] = '编辑';
        $data['form'] = $this->build_form($form, $value);
        $data['script'] = $this->build_script($form, $args);
        return view('/admins/groups/edit', $data);
    }

    public function save_edit(Request $request)
    {
        $id = (int)$request->id;
        if (!$id) return $this->errMsg(1, '数据错误');
        $data = $this->check($this->form(), $request);
        if (!is_array($data)) return $data;
        $check = DB::table('admin_group')->where('title', $data['title'])->first();
        if ($check && $check->title !== $data['title']) return $this->errMsg(1, '角色名称重复');
        $data['rights'] = json_encode(array_map('intval', array_values((array)$request->rights)));
        DB::table('admin_group')->where('id', $id)->update($data);
        return $this->errMsg(0, '修改成功');
    }

    public function del(Request $request)
    {
        $id = (array)$request->id;
        if (!$id) return $this->errMsg(1, '请选择数据');
        $res = DB::table('admin_group')->whereIn('id', $id)->delete();
        if (!$res) return $this->errMsg(1, '删除失败');
        return $this->errMsg(0, '删除成功');
    }
}
